import logging
import random

from django import http
from django_redis import get_redis_connection
from django.views import View

from duomei_shop.utils.response_code import RETCODE
from . import constants
from verifications.libs.captcha.captcha import captcha
from celery_tasks.sms.tasks import ccp_send_sms_code
from .libs.yuntongxun.ccp_sms import CCP
# Create your views here.


logger = logging.getLogger('django')
#短信验证码校验
class SMSCodeView(View):

    def get(self,request,mobile):
        # 获取参数 image_code，uuid
        image_code=request.GET.get('image_code')
        uuid=request.GET.get('uuid')

        # 校验参数
        if not all([image_code,uuid]):
            return http.JsonResponse({'code': RETCODE.NECESSARYPARAMERR, 'errmsg': '缺少必传参数'})

        # 创建连接到redis的对象
        redis_conn=get_redis_connection('verify_code')
        # 提取图形验证码
        image_code_server=redis_conn.get('img_%s' %uuid)
        # 图形验证码过期或者不存在
        if image_code_server is None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码失效'})
        #2222222222 删除图形验证码，避免恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' %uuid)
        except Exception as e:
            logger.error(e)
        # 对比图形验证码
        image_code_server=image_code_server.decode()
        if image_code.lower() != image_code_server.lower() :
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码错误'})

        # 生成短信验证码：生成6位数验证码
        sms_code='%06d' %random.randint(0,999999)
        logger.info(sms_code)

        # # 保存短信验证码
        # redis_conn.setex('sms_%' %mobile,constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # # 重新写入send_flag
        # redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 创建Redis管道
        pl = redis_conn.pipeline()
        # 将Redis请求添加到队列
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
         # 执行请求
        pl.execute()

        # 发送短信验证码

        CCP().send_template_sms(mobile,[sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60],constants.SEND_SMS_TEMPLATE_ID)
        #ccp_send_sms_code.delay(mobile, sms_code)
        # 响应结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送短信成功'})











#验证码校验
class ImageCodeView(View):

    def get(self,request,uuid):

        text,image=captcha.generate_captcha()

        redis_conn=get_redis_connection('verify_code')

        redis_conn.setex('img_%s' %uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        return http.HttpResponse(image, content_type='image/jpg')
